package IO_;

import java.io.*;
import java.util.Scanner;

/**
 * 扫描指定⽬录，并找到名称或者内容中包含指定字符的所有普通⽂件（不包含⽬录）
 */
public class Io09 {
    public static void main(String[] args) {
        System.out.println("请输入要查找的目录:");
        Scanner scan=new Scanner(System.in);
        String src=scan.next();
        File file = new File(src);
        if(!file.isDirectory()){
            System.out.println("输入目录有误!!");
            return;
        }
        System.out.println("请输入要查找文件:");
        String s1=scan.next();
        scanFile(file,s1);
    }
    private static void scanFile(File srcfile,String s){
        File[] files = srcfile.listFiles();
        if(files==null){
            return;
        }
        for(File f:files){
            if(f.isFile()){
                //是文件,进行搜索,是否有要找到内容
                    SearchWord(f,s);
            }else if(f.isDirectory()){
                //是目录 继续递归寻找文件
                scanFile(f,s);
            }
        }
    }

    private static void SearchWord(File f, String s) {
        try(InputStream inputStream=new FileInputStream(f)){
            StringBuilder stringBuilder=new StringBuilder();
            while(true){
                byte[] buffer=new byte[1024];
                int n = inputStream.read(buffer);
                if(n==-1){
                    break;
                }
                String str=new String(buffer,0,n);
                stringBuilder.append(str);
            }
            if(stringBuilder.indexOf(s)!=-1){
                System.out.println("找到了,文件路径为: "+f.getAbsolutePath());
            }else{
                System.out.println(f.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
